// getParam:上个页面传的参数  currentWin:需要关闭的当前window   isClose:当前为打开页面时的查询还是关闭页面时的查询
// 
var studyTimeRecord;
var studyTimeLine;
study_courseTimeRecordFun = function(getParam, currentWin, isClose,dataFunType){
    var isLine = '1';
    var uid = $api.getStorage('cfnetppuid');
    var jid = $api.getStorage('cfnetppjxid');
    api.addEventListener({
        name: 'moocChapterBackNotifi'
    }, function(ret, err) {
        requestTimeControlFun();
    });
    // 添加学习纪录，需要先同步学习纪录(上个页面传入的etime)，进入该页面后，每分钟执行一次学习纪录的上传，当上传成功时，插入一条数据到t_study_course_record_detail表中，代表学习了一分钟，若上传不成功，插入数据时需标记当前纪录为本地数据，每隔5分钟，查询一次数据库中未上传成功的纪录并一次性上传服务器，同时修改这些数据为服务器数据
    requestTimeControlFun = function(){
        var timeParam = {
            uid: uid,
            jid: jid,
            cid: getParam.cid,
            vid: getParam.vid,
            sources:2,
            pid:getParam.pid
        };
        // console.log(JSON.stringify(timeParam)+'\n'+study_course_upload_record);
        // alert('url:'+study_course_upload_record+'\n'+JSON.stringify(timeParam));
        api.ajax({
            url: study_course_upload_record,
            method: 'post',
            timeout: 30,
            dataType: 'json',
            returnAll:false,
            data:{
                values:timeParam
            }
        },function(ret,err){
            console.log("学习记录追踪:"+JSON.stringify(ret));
            if (ret.status == 1 || ret.status == true) {
                insertDataFun(ret.learnstatus);
            }
        });
    }
    // 学习时间纪录(需每分钟往数据库中存入一次)
    insertDataFun = function(statusSubmit){
        var timestamp = (new Date()).valueOf();
        // alert('------'+timestamp);
        var insertDataParam = {
            uid: uid,
            jid: jid,
            pid: getParam.pid,
            cid: getParam.cid,
            vid: getParam.vid,
            instime: timestamp,
            submitstatus: statusSubmit
        }

        openDB(function(ret, err){
            if (ret.status) {
                insertData('t_study_course_record_detail', insertDataParam, function(ret, err){
                    if (ret.status) {
                        // alert('插入成功' + ret.status);
                    }else{
                        // alert(err.msg);
                    }
                });
            }
        });
    }
    isTimeInsertFun = function(isClose){
        if(isClose == 'false'){
            // 每分钟纪录一次时间
            studyTimeRecord = setInterval(function(){
                    // insertDataFun('2');
                requestTimeControlFun();
            },60000);
        }
        else{
            clearInterval(studyTimeRecord);
            api.closeWin({
                name: currentWin
            });
        }
    }
    islineFun = function(isClose){
        if(isClose == 'false'){
            // 每分钟纪录一次时间
            studyTimeLine=setInterval(function(){
                insertDataFun('2');
            },60000);
        }else{
            // insertDataFun();
            clearInterval(studyTimeLine);
            api.closeWin({
                name: currentWin
            });
        }
    }
    selectDataFun = function(isClose){
        // 需要再添加个是否上传服务器成功的字段，此处需要查询所有上传服务器成功的总条数(每隔五分钟需要查询一次表中未上传成功的条数重新上传)
        var selectSqlString = 'select * from t_study_course_record_detail where uid=' + uid + ' and vid='+getParam.vid;
        openDB(function(ret, err){
            if(ret.status){
                selectSQL(selectSqlString, function(ret, err){
                    // alert(JSON.stringify(ret));
                    // alert(JSON.stringify(getParam));
                    if(ret.status){
                        var etime = getParam.etime;
                        if (etime == null || etime == '' || etime == 'null') {
                            etime = '0';
                        }
                        // 当表中总条数大于课时时长时，则不再往数据表中插入，说明课程已学完,否则，则返回且插入数据
                        if(parseInt(ret.data.length) + parseInt(etime) >= parseInt(getParam.ctime)){
                        }else{
                            islineFun(isClose);
                        }

                        if(isClose == 'true'){
                            if(getParam.status != 1){
                                api.sendEvent({
                                    name: 'courseStudiedFinishNotifi',
                                    extra: {
                                        // pid: getParam.pid,
                                        vid: getParam.vid,
                                        cid: getParam.cid,
                                        ctime: getParam.ctime,
                                        etime: parseInt(ret.data.length) + parseInt(etime),
                                        status: ret.data.length>0?parseInt( ret.data[0].submitstatus):2,
                                        studyType:'0'
                                    }
                                });
                                var cid = getParam.cid;
                                var vid = getParam.vid;
                                var timenum = parseInt(ret.data.length) + parseInt(etime);
                                var origtime = parseInt(getParam.ctime);
                                var status = '2';
                                // alert('timenum'+timenum+'\n'+'origtime'+origtime);
                                if (timenum >= origtime) {
                                    status = '1';
                                    timenum = origtime;
                                }
                        
                               // var sql = "UPDATE t_study_course_record SET submitstatus=2, status=" + status + ", crid=" + getParam.crid + ",timenum=" + timenum + " WHERE vid=" + vid + " and uid = " + uid + ";";
                                var sql = "UPDATE t_study_course_record SET submitstatus=2, status=" + status + ",timenum=" + timenum + " WHERE vid=" + vid + " and uid = " + uid + ";";
                                // alert(sql);
                                executeSQL(sql, function(ret, err){
                                    if (ret.status) {
                                        // alert('update:'+JSON.stringify(ret));
                                        var allChapterSql = "SELECT status,vid FROM t_study_course_record WHERE cid=" + cid + " AND uid=" + uid + " AND types=1;";
                                        selectSQL(allChapterSql, function(ret, err){
                                            if (ret.status) {
                                                var chapterStatuses = ret.data;
                                                if (chapterStatuses.constructor == Array) { 
                                                    var j = 0;
                                                    var allChapters = 0;
                                                    var studiedChapter = 0;  
                                                    for (var i = 0; i < chapterStatuses.length; i++) {
                                                        var chapterData = chapterStatuses[i];
                                                        contentTypeWithVid(chapterData, function(currentChapterData, contentType){
                                                            j++;
                                                            if (contentType == 'video' || contentType == 'richtext' || contentType == 'doc') {
                                                                allChapters++;
                                                                if(currentChapterData.status == 1){
                                                                    studiedChapter++;
                                                                }
                                                            }
                                                            if(j == chapterStatuses.length){
                                                                if(studiedChapter == allChapters){//学完
                                                                    api.sendEvent({
                                                                        name: 'allChapterStudiedNotifi',//所有章节学完通知
                                                                        extra: {cid: cid}
                                                                    });
                                                                }
                                                                //计算进度 
                                                                var schedule = Math.ceil((studiedChapter / allChapters) * 100);
                                                                if (schedule > 100) {
                                                                    schedule = 100;
                                                                }
                                                                api.sendEvent({
                                                                    name: 'refreshCourseSchedule',//通知当前学习进度
                                                                    extra: {
                                                                        schedule: schedule,
                                                                        courseid: cid,
                                                                        pid: getParam.pid
                                                                    }
                                                                });    
                                                                //更新进度                                   
                                                                var updateSql = "UPDATE t_study_course SET cjd=" + schedule+ " WHERE courseid=" + cid + " AND uid=" + uid + ";";
                                                                executeSQL(updateSql, function(ret, err){
                                                                    clearInterval(studyTimeRecord);
                                                                    api.closeWin({
                                                                        name: currentWin
                                                                    });
                                                                });
                                                            }
                                                        });
                                                    } 
                                                    // var examSql = "SELECT examid FROM t_study_exam WHERE courseid=" + cid + + " AND uid=" + uid + ";";
                                                    // selectSQL(examSql, function(ret, err){
                                                    //     var submitstatusStr = ", submitstatus=2";
                                                    //     if (ret.status) {
                                                    //         if (ret.data != null && ret.data != '' && ret.data != undefined) {
                                                    //             if (ret.examid != '' && ret.examid != 0) {
                                                    //                 submitstatusStr = "";
                                                    //             }
                                                    //         }
                                                    //     }
                                                    //     // var courseSql = "UPDATE t_study_course_record SET timenum=" + alltime + submitstatusStr + " , crid=" + getParam.crid + " WHERE vid=0 AND cid=" + cid + " AND uid=" + uid + ";";
                                                    //     var courseSql = "UPDATE t_study_course_record SET timenum=" + alltime + submitstatusStr + " WHERE vid=0 AND cid=" + cid + " AND uid=" + uid + ";";
                                                    //     executeSQL(courseSql, function(ret, err){
                                                    //         api.sendEvent({
                                                    //             name: 'uploadCourseRecordNotifi'
                                                    //         });
                                                    //         clearInterval(studyTimeRecord);
                                                    //         api.closeWin({
                                                    //             name: currentWin
                                                    //         });
                                                    //     });
                                                    // });
                                                }else{
                                                    clearInterval(studyTimeRecord);
                                                    api.closeWin({
                                                        name: currentWin
                                                    });
                                                }
                                            }else{
                                                clearInterval(studyTimeRecord);
                                                api.closeWin({
                                                    name: currentWin
                                                });
                                            }
                                        });
                                    }else{
                                        clearInterval(studyTimeRecord);
                                        api.closeWin({
                                            name: currentWin
                                        });
                                    }
                                });
                            }else{
                                clearInterval(studyTimeRecord);
                                api.closeWin({
                                    name: currentWin
                                });
                            }
                        }
                    }else{
                        islineFun(isClose);
                    }
                });
            }else{
                islineFun(isClose);
            }
        });
    }
    // console.log('++++++++'+dataFunType);
    if(isClose=='true'){
        selectDataFun(isClose);
        clearInterval(studyTimeRecord);
    }else{
        isTimeInsertFun(isClose);
        // if (getParam.ctime == '0') {
        //     requestTimeControlFun();
        // }
    }
}
function contentTypeWithVid(chapterData,callBack){
    var sql = "SELECT content_type FROM t_study_chapter WHERE chapter_id=" + chapterData.vid + ";";
    selectSQL(sql, function(ret, err){
        if (ret.status && ret.data != undefined && ret.data != null && ret.data != '') {
            var chaptertag = ret.data[0].content_type;
            callBack(chapterData,chaptertag);
        }
    });
}
/*
    var allChapterSql = "SELECT timenum FROM t_study_course_record WHERE cid=" + cid + " AND uid=" + uid + " AND types=1;"; 
    selectSQL(allChapterSql, function(ret, err){
if (ret.status) {
// var chapterTimenums = ret.data;
var chapterStatuses = ret.data;
// if (chapterTimenums.constructor == Array) {
if (chapterStatuses.constructor == Array) {                                              
// var alltime = 0;
// for (var i = 0; i < chapterTimenums.length; i++) {
//     var studiedTime = chapterTimenums[i].timenum;
//     if (studiedTime == '' || studiedTime == undefined || studiedTime == null || studiedTime == NaN || studiedTime == 'NaN') {
//         studiedTime = 0;
//     }
//     alltime += parseInt(studiedTime);
// }
//                                    var courseRecordSql = "SELECT origtime FROM t_study_course_record WHERE vid=0 AND cid=" + cid + " AND uid=" + uid + ";";
//                                    selectSQL(courseRecordSql, function(ret, err){
//                                        if (ret.status) {
//                                            //课程学习时间
//                                            var courseStudyTime = parseInt(ret.data[0].origtime);
//                                            if (alltime >= courseStudyTime) {
//                                                api.sendEvent({
//                                                    name: 'allChapterStudiedNotifi',//所有章节学完通知
//                                                    extra: {cid: cid}
//                                                });
//                                            }
//                                        }
//                                    });
//                                    var courseTimeSql = "SELECT alltime FROM t_study_course_info WHERE courseid=" + cid + ";";
//                                    selectSQL(courseTimeSql, function(ret, err){
//                                        if (ret.status) {
//                                            var ctime = parseFloat(ret.data[0].alltime);
//                                            // alert(alltime + '\n' + ctime);
//                                            var schedule = Math.ceil((parseFloat(alltime) / ctime) * 100);
//                                            if (schedule > 100) {
//                                                schedule = 100;
//                                            }
//                                            api.sendEvent({
//                                                name: 'refreshCourseSchedule',
//                                                extra: {
//                                                    schedule: schedule,
//                                                    courseid: cid
//                                                }
//                                            });

//                                            var updateSql = "UPDATE t_study_course SET cjd=" + schedule+ " WHERE courseid=" + cid + " AND uid=" + uid + ";";
                                            // executeSQL(updateSql, function(ret, err){
                                            //  if (ret.status) {
                                            //  }else{
                                            //  }
                                            // });
//                                        }
//                                    });
*/